<template>
	<view class="html2Canvas">
		<!-- 需要生成图片的模板 -->
		<view class="canvas-module" id="pagePoster">
			<img :src="codeBg" @load="load" style="width: 100%;height: 100%;position: absolute;z-index: 1;" />
			<view class="canvas-content">
				<view class="section">
					<view class="code-img">
						<img :src="codeImage" alt="" />
					</view>
					<view class="detail-text">
						<!-- {{text}} -->
					</view>
				</view>
			</view>
		</view>
		<view class="flex-aro bottomBtn">
			<view class="btn" @click="draw">生成图片</view>
			<view class="btn share" @click="yqzx_url">邀请挣钱</view>
			<!-- <view class="btn share" @click="shareShow">邀请挣钱</view> -->
		</view>
		<!-- <view class="generate-image" @click="canvasImage.generateImage">生成图片</view> -->

		<!-- 生成的图片 -->
		<view v-if="posterUrl" class="section-result flex-x-center flex-y-center" @click="posterhide">
			<!-- H5采用长按保存图片，app就可以通过按钮保存或分享，微信小程序需要连接到H5再进行长按保存 -->
			<!-- 图片使用 img 标签会好些，可以更好的兼容base64位图片连接的显示 -->
			<img class="image" :src="posterUrl" alt="" @load="_hideLoading" />
			<!-- #ifdef APP-PLUS -->
			<view class="generate-image" @click="loadBase64Url">保存图片到手机</view>
			<!-- #endif -->
		</view>
		<!-- 分享箭头 -->
		<view class="popShare" v-if="sharebox==true" @click="shareShow">
			<view class="box">
				<image src="@/static/img/jiantou.png"></image>
				<view class="text">点击右上角</view>
				<view class="text">立即分享</view>
			</view>

		</view>
		<canvas canvas-id="myCanvas" v-if="show" class="myCanvas"
			:style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' , position: 'fixed', left: '2000px', top: '2000px' ,'z-index':2}"></canvas>
			<activityModal />
	</view>

</template>
<!-- <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> -->
<script>
	import {
		shareQrcode,
		getWxConfig
	} from '../../apirequest/api.js';
	import {
		getNodeStyle,
		downImg,
		draw_img,
		getbase64,
		draw_rech
	} from "@/utils/draw.js";
	// var jWeixin = require('jweixin-module')
	import {
		pathToBase64,
		base64ToPath
	} from '@/common/imageTools/index.js';

	export default {
		data() {
			return {
				canvasWidth: 0,
				show: false,
				canvasHeight: "",
				posterUrl: '', // 生成画布的图片
				codeImage: '', //二维码
				codeBg: '', //背景图
				codeImage1: '', //二维码
				codeBg1: '', //背景图
				sharebox: false,
				shareOption: {}
			}
		},
		mounted() {
			if (window.location.href.indexOf("?#") < 0) {
				window.location.href = window.location.href.replace("#", "?#");
			}
		},
		onLoad() {
			this.loadData();
		},
		onShow() {
			let url = window.location.href.replace(/[?&]code=(\w+)/i, '').replace(/&state=fanpingsanguo/ig, '');
			window.history.replaceState(null, '', url);
			this.share();
		},
		methods: {
			load(e) {
				this.canvasWidth = e.detail.width / 2;
				this.canvasHeight = e.detail.height / 2;
				this.show = true
			},
			async draw(callback) {
				try {
					const _this = this;
					uni.showLoading({
						mask: true,
					});
					const haibaoNode = await downImg(this.codeBg1)
					const qrcodeUrl = await downImg(this.codeImage1);
					let top = 0,
						left = 0;
					this.ctx = uni.createCanvasContext("myCanvas");
					this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); // 清空整个画布
					await draw_rech(this.ctx, 0, 0, this.canvasWidth, this.canvasHeight, 0, '#fff')
					await draw_img(
						this.ctx,
						haibaoNode,
						0,
						0,
						this.canvasWidth,
						this.canvasHeight
					);
					await draw_img(
						this.ctx,
						qrcodeUrl,
						this.canvasWidth / 2 + 90,
						this.canvasHeight - 135,
						120,
						120
					);
					this.ctx.restore()
					this.ctx.draw();
					setTimeout(() => {
						uni.canvasToTempFilePath({
								x: 0,
								y: 0,
								width: this.canvasWidth,
								height: this.canvasHeight,
								destWidth: this.canvasWidth * 3,
								destHeight: this.canvasHeight * 3,
								fileType: "jpg",
								canvasId: "myCanvas",
								complete: (res) => {
									uni.hideLoading()
									console.log(res);
									if (res.errMsg ==
										'canvasToTempFilePath:fail fail canvas is empty'
									) {
			
										// #ifdef MP-WEIXIN
										uni.showToast({
											title: '导出失败'
										})
										// #endif
										return
									}
									// 图片提示跨域 H5保存base64失败，APP端正常输出临时路径
									if (res.tempFilePath) {
										_this.ctx.clearRect(
											0,
											0,
											_this.canvasWidth,
											_this.canvasHeight
										); // 清空整个画布
										const saveFileUrl = res
											.tempFilePath;
										uni.previewImage({
											urls: [saveFileUrl]
										})
			
									}
								},
							},
							this
						);
					}, 1000)
			
				} catch (err) {
					console.log(err);
				}
			},
			yqzx_url: function() {
				uni.navigateTo({
					url: '/pages/revenueRule/revenueRule'
				})
			},
			//分享
			share: function() {
				let that = this;
				getWxConfig({
					url: encodeURI(location.href)
				}).then((res) => {
					if (res.code == 1) {
						var share_url = res.data.share_url;
						var desc = "长按识别二维码，领取您的免费外卖吧";
						var title = "扫码有福利";
						//var share_img = '/static/img/logo.png';
						var share_img = "";
						this.shareOption = {
							share_url: res.data.share_url,
							desc: "长按识别二维码，领取您的免费外卖吧",
							title: "扫码有福利",
							share_img: ""
						}
						// #ifdef h5
						jWeixin.config({
							debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
							appId: res.data.appId,
							timestamp: res.data.timestamp,
							nonceStr: res.data.nonceStr,
							signature: res.data.signature,
							jsApiList: ['checkJsApi', 'updateAppMessageShareData',
								'updateTimelineShareData', 'onMenuShareTimeline',
								'onMenuShareAppMessage'
							]
						});
						jWeixin.ready(function() {
							// config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
							//分享至微信好友
							jWeixin.updateAppMessageShareData({
								title: title, // 分享标题
								desc: desc, // 分享描述
								link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
								imgUrl: share_img, // 分享图标
								type: '', // 分享类型,music、video或link，不填默认为link
								dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
								success: function() {
									// 用户点击了分享后执行的回调函数
								}
							});
							//分享朋友圈
							jWeixin.updateTimelineShareData({
								title: title, // 分享标题
								desc: desc,
								link: share_url, // 分享链接
								imgUrl: share_img, // 分享图标
								success: function() {
									// 用户确认分享后执行的回调函数
									console.log('进入分享');
								},
								cancel: function() {
									// 用户取消分享后执行的回调函数
									console.log('取消分享');
								}
							});

							//分享至微信好友
							jWeixin.onMenuShareTimeline({
								title: title, // 分享标题
								desc: desc, // 分享描述
								link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
								imgUrl: share_img, // 分享图标
								type: '', // 分享类型,music、video或link，不填默认为link
								dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
								success: function() {
									// 用户点击了分享后执行的回调函数
								}
							});
							//分享朋友圈
							jWeixin.onMenuShareAppMessage({
								title: title, // 分享标题
								desc: desc,
								link: share_url, // 分享链接
								imgUrl: share_img, // 分享图标
								success: function() {
									// 用户确认分享后执行的回调函数
									console.log('进入分享');
								},
								cancel: function() {
									// 用户取消分享后执行的回调函数
									console.log('取消分享');
								}
							});
						});
						jWeixin.error(function(res) {
							// config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
							console.log('验证失败');
							console.log(res);
						});
						// #endif

					}
				});

			},
			//获取数据
			loadData: function() {
				shareQrcode({}).then((res) => {
					if (res.code == 1) {
						this.codeImage = res.data.codeImage;
						this.codeBg = res.data.codeBg;
						this.codeImage1 = res.data.codeImage;
						this.codeBg1 = res.data.codeBg;
						this.turnBase64Image(this.codeImage, 'codeImage');
						this.turnBase64Image(this.codeBg, 'codeBg')
					} else {
						uni.showToast({
							title: res.msg,
							icon: "error"
						})
						setTimeout(function() {
							uni.navigateBack({
								delta: 0
							});
						}, 1000)
					}
				}).catch(err => {
					console.log(err)
				})
			},
			shareShow() {
				this.sharebox = !this.sharebox
			},
			posterhide() {
				this.posterUrl = '';
			},
			/* 将base64 位的图片路径转换为 临时路径 */
			loadBase64Url() {
				const imageStr = this.posterUrl;
				base64ToPath(imageStr)
					.then(path => {
						this.saveImage(path);
					})
					.catch(error => {
						console.error('临时路径转换出错了：', error);
					});
			},
			// 保存图片到手机相册
			saveImage(filePath) {
				uni.saveImageToPhotosAlbum({
					filePath, // 需要临时文件路径，base64无法保存
					success: () => {
						this._showToast('保存图片成功');
					},
					fail: () => {
						this._showToast('保存失败，请重试');
					}
				});
			},
			// 将图片转为base 64 位url
			turnBase64Image(img, key) {
				uni.getImageInfo({
					src: img,
					success: image => {
						pathToBase64(image.path)
							.then(base64 => {
								this[key] = base64;
							})
							.catch(error => {
								console.log('转换失败：', error);
							});
					},
					fail: err => {
						console.log('将本地图片转为base 64报错:', err);
					}
				});
			},
			// 获取生成的base64 图片路径
			receiveRenderData(val) {
				this.posterUrl = val.replace(/[\r\n]/g, ''); // 去除base64位中的空格
			},

			// 显示loading
			_showLoading(str) {
				this.posterUrl = '';
				uni.showLoading({
					title: str
				});
			},

			// 隐藏loading
			_hideLoading() {
				uni.hideLoading();

				// #ifdef H5
				this._showToast('长按保存图片');
				// #endif
			},

			// 报错alert
			_errAlert(content) {
				uni.showModal({
					title: '提示',
					content: content
				});
			},

			// 提示弹窗
			_showToast(msg) {
				uni.showToast({
					title: msg,
					icon: 'none'
				});
			}

		}
	}
</script>
<script lang="renderjs" module="canvasImage">
	import html2canvas from '@/common/html2canvas.min.js'
	export default {
		methods: {
			DPR() { // 获取设备dpi
				if (window.devicePixelRatio && window.devicePixelRatio > 1) {
					return window.devicePixelRatio;
				}
				return 1;
			},
			// 生成图片需要调用的方法
			generateImage(e, ownerFun) {
				ownerFun.callMethod('_showLoading', '正在生成图片') // 生成图片的 loading 提示
				setTimeout(() => {
					const dom = document.getElementById('pagePoster') // 需要生成图片内容的 dom 节点
					const box = window.getComputedStyle(dom);
					const width = parseInt(box.width, 10);
					const height = parseInt(box.height, 10);
					// console.log(width)
					// console.log(height)
					// const scaleBy = this.DPR();
					// console.log(scaleBy)
					// const canvas = document.createElement('canvas');
					// canvas.width = width * scaleBy;
					// canvas.top = 0;
					// canvas.scrollX = 0;
					// canvas.scrollY = 0;
					// canvas.height = height * scaleBy;
					// canvas.style.width = `${width}px`;
					// canvas.style.height = `${height}px`;
					// const context = canvas.getContext('2d');
					// context.scale(scaleBy, scaleBy);
					html2canvas(dom, {
						width: width, // canvas宽度
						height: height, // canvas高度
						// canvas,
						scrollX: 0,
						scrollY: 0,
						dpi: 300,
						x: 0, // x坐标
						y: 0,
						scroll: 3,
						useCORS: true, //支持跨域
					}).then((imgDom) => {
						// 生成成功
						// html2canvas 生成成功的图片链接需要转成 base64位的url
						ownerFun.callMethod('receiveRenderData', imgDom.toDataURL('image/png'), 1.0)
					}).catch(err => {
						// 生成失败 弹出提示弹窗
						ownerFun.callMethod('_errAlert', `【生成图片失败，请重试】${err}`)
					})
				}, 300)
				console.log(document.getElementById('pagePoster'))
			}
		}
	}
</script>


<style>
	page {
		background: #FFFFFF;
		margin-bottom: 150rpx;
	}

	image,
	img {
		width: 100%;
		height: 100%;
	}

	.html2Canvas .canvas-module {
		box-shadow: 0 0 4px 0 rgba(56, 56, 56, .14);
		border-radius: 6px;
		position: relative;
		width: 640rpx;
		height: 1138rpx;
		margin: 16px auto;
	}

	.canvas-module .canvas-content {
		padding: 240upx 40upx;
	}

	.section .code-img {
		width: 170upx;
		height: 170upx;
		position: absolute;
		bottom: 30rpx;
		right: 50rpx;
		z-index: 2;
	}

	.section .detail-text {
		font-size: 30rpx;
		line-height: 1.4;
		color: #666;
		margin-top: 12rpx;
		text-align: center;
		color: #fc2a34;
		font-weight: 700;
	}

	.generate-image {
		height: 98rpx;
		margin: 30rpx 30rpx;
		background-color: #41b783;
		font-size: 32rpx;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 12rpx;
	}

	.section-result {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		background: rgba(0, 0, 0, 0.6);
		padding: 30rpx 0;
		z-index: 999;
	}

	.section-result img {
		width: 640rpx;
		height: 1138rpx;
	}

	.section-result .title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
	}

	.bottomBtn {
		padding: 20rpx 0;
		width: 100%;
		background: #fff;
	}

	.bottomBtn .btn {
		border-radius: 50upx;
		font-size: 36rpx;

		background: linear-gradient(to right, #f5af20, #fee378);
		color: #fff;
		padding: 15upx 80upx;

	}

	.bottomBtn .share {
		background: linear-gradient(to right, #f91302, #fe8782);
		color: #fff;
	}

	.popShare {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		background: rgba(0, 0, 0, 0.6);
	}

	.popShare .box {
		position: fixed;
		top: 150upx;
		right: 50upx;
		color: #fff;
		text-align: center;

	}

	.popShare .box image {
		width: 300upx;
		height: 300upx;
	}

	.popShare .box .text {
		font-size: 50rpx;
		font-weight: 700;
	}
</style>